package com.ct.gd.passport.common.mock;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.lang3.CharSet;
import org.apache.commons.lang3.CharSetUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.os.Environment;

import com.ct.gd.passport.common.connect.CtServer;
import com.ct.gd.passport.domain.CameraSubmitInfo;
import com.ct.gd.passport.util.TelephonyState;
import com.up91.common.android.helper.L;

public class HttpConnectClient {

	private static final String CHARSET = HTTP.UTF_8;
	private static HttpClient httpClient;

	private static final String twoHyphens = "--";
	// 数据分隔符 可能是任意字符串
	private static final String boundary = "fD4fH3gL0hK7aI6";
	// 行结束符
	private static final String lineEnd = "/r/n";

	private HttpConnectClient() {
	}

	public static synchronized HttpClient getHttpClient() {
		if (null == httpClient) {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, false);
			HttpProtocolParams
					.setUserAgent(
							params,
							"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
									+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 1000);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 10000);

			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			httpClient = new DefaultHttpClient(conMgr, params);
		}
		((DefaultHttpClient) httpClient).getCookieStore().clear();
		return httpClient;
	}

	public static String connect(ConnectRequest request) {
		return connect(request, null);
	}

	public static String connect(ConnectRequest request, Header[] headers) {
		HttpResponse response = connectGetResponse(request, headers);
		return getContent(response);
	}

	public static HttpResponse connectGetResponse(ConnectRequest request,
			Header[] headers) {
		List<? extends NameValuePair> params = request.getParams();
		HttpResponse response = null;
		if (request.method.equals("POST")) {
			response = post(request.getUrl(), params, headers);
		} else {
			response = get(request.getUrl(), headers);
		}
		return response;
	}

	public static HttpResponse post(String url,
			List<? extends NameValuePair> formparams, Header[] headers) {
		try {
			for (NameValuePair pair : formparams) {
				L.i("param", pair.getName() + " = " + pair.getValue());
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
					CHARSET);
			HttpPost request = new HttpPost(url);
			request.setEntity(entity);
			if (headers != null) {
				request.setHeaders(headers);
			}
			// 发送请求
			HttpClient client = getHttpClient();
			HttpResponse response = client.execute(request);
			return response;
		} catch (UnsupportedEncodingException e) {
			return null;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("连接失败，请重试", e);
		} catch (Exception e) {
			throw new RuntimeException("连接失败，请稍候重试", e);
		}
	}

	public static HttpResponse get(String url, Header[] headers) {
		try {
			HttpGet request = new HttpGet(url);
			if (headers != null) {
				request.setHeaders(headers);
			}
			HttpClient client = getHttpClient();
			HttpResponse response = client.execute(request);
			return response;
			// if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
			// {
			// throw new RuntimeException("请求失败");
			// }
			// HttpEntity resEntity = response.getEntity();
			// return (resEntity == null) ? null :
			// EntityUtils.toString(resEntity, CHARSET);
			// } catch (UnsupportedEncodingException e) {
			// return null;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			throw new RuntimeException("连接失败,请稍候重试", e);
		} catch (Exception e) {
			throw new RuntimeException("连接失败,请稍候重试", e);
		}
	}

	/**
	 * 获取字节流数据
	 * 
	 * @param url
	 * @param headers
	 * @return
	 */
	public static byte[] getBytes(String url, Header[] headers) {
		try {
			HttpGet request = new HttpGet(url);
			HttpClient client = getHttpClient();
			if (headers != null) {
				request.setHeaders(headers);
			}
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				throw new RuntimeException("请求失败");
			}
			HttpEntity resEntity = response.getEntity();
			return (resEntity == null) ? null : EntityUtils
					.toByteArray(resEntity);
		} catch (UnsupportedEncodingException e) {
			return null;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			throw new RuntimeException("连接失败,请稍候重试", e);
		} catch (Exception e) {
			throw new RuntimeException("连接失败,请稍候重试", e);
		}
	}

	public static final Header[] getHeaders(HttpResponse response) {
		if (response != null) {
			return response.getAllHeaders();
		}
		return null;
	}

	public static final String getContent(HttpResponse response) {
		if (response == null
				|| response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new RuntimeException("请求失败");
		}
		try {
			HttpEntity resEntity = response.getEntity();
			return (resEntity == null) ? null : EntityUtils.toString(resEntity,
					CHARSET);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("连接失败,请稍候重试", e);
		}
	}

	// // --用于多段提交图片的模块

	public static String connectMultpart(ConnectRequest request, String imgKey,
			String imgName, String imgType, Bitmap bitmap) {
		List<? extends NameValuePair> params = request.getParams();
		String response = null;
		response = multipart(request.getUrl(), params, null, imgKey, imgName,
				imgType, bitmap);
		return response;
	}

	public static String multipart(String actionUrl,
			List<? extends NameValuePair> formparams, Header[] headers,
			String imgKey, String imgName, String imgType, Bitmap bitmap) {
		HttpURLConnection conn = null;
		DataOutputStream output = null;
		BufferedReader input = null;
		try {
			URL url = new URL(actionUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(120000);
			conn.setDoInput(true); // 允许输入
			conn.setDoOutput(true); // 允许输出
			conn.setUseCaches(false); // 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + boundary);
			conn.connect();
			output = new DataOutputStream(conn.getOutputStream());
			for (NameValuePair pair : formparams) {
				L.i("param", pair.getName() + " = " + pair.getValue());
				output.writeBytes(getMultipartKVPair(pair.getName(),
						pair.getValue()));
			}
			writeMultipartImgPair(output, imgKey, imgName, imgType, bitmap);
			output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);// 数据结束标志
			output.flush();
			int code = conn.getResponseCode();
			if (code != 200) {
				throw new RuntimeException("请求‘" + actionUrl + "’失败！");
			}
			input = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			StringBuilder response = new StringBuilder();
			String oneLine;
			while ((oneLine = input.readLine()) != null) {
				response.append(oneLine + lineEnd);
			}
			return response.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 统一释放资源
			try {
				if (output != null) {
					output.close();
				}
				if (input != null) {
					input.close();
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
	}

	private static final String getMultipartKVPair(String key, String value) {
		StringBuilder sb = new StringBuilder();
		sb.append(twoHyphens + boundary + lineEnd);
		sb.append("Content-Disposition: form-data;name=\"" + key + "\""
				+ lineEnd);
		sb.append(lineEnd);
		sb.append(value).append(lineEnd);
		return sb.toString();
	}

	private static final void writeMultipartImgPair(DataOutputStream dos,
			String key, String name, String type, Bitmap bitmap) {
		StringBuilder sb = new StringBuilder();
		sb.append(twoHyphens + boundary + lineEnd);
		sb.append("Content-Disposition: form-data;name=\"" + key
				+ "\";filename=\"" + name + "\"" + lineEnd);
		sb.append("Content-Type: " + type + lineEnd); // 需要设置图片类型
		sb.append(lineEnd);

		ByteArrayOutputStream bits = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bits);
		try {
			dos.writeBytes(sb.toString());
			dos.write(bits.toByteArray());
			dos.writeBytes(lineEnd);
		} catch (Exception e) {
			L.e("writeMultipartImgPair", "图片上传参数写入错误 " + e.getMessage());
		} finally {
			try {
				bits.close();
			} catch (Exception e) {
			}
		}
	}

	// public static final String submitPic(List<? extends
	// org.apache.commons.httpclient.NameValuePair> formparams){
	// try {
	// File f = new
	// File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg");
	// System.out.println("文件长度:"+f.length());
	// PostMethod filePost = new PostMethod(
	// "http://121.9.201.145:81/rest/passport/capture.php");
	// Part[] parts = {new FilePart("pic", f) };
	// filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost
	// .getParams()));
	// for (org.apache.commons.httpclient.NameValuePair pair : formparams) {
	// L.i("param", pair.getName() + " = " + pair.getValue());
	// filePost.addParameter( pair);
	// }
	//
	// org.apache.commons.httpclient.HttpClient clients = new
	// org.apache.commons.httpclient.HttpClient();
	// int status = clients.executeMethod(filePost);
	// BufferedReader rd = new BufferedReader(new InputStreamReader(
	// filePost.getResponseBodyAsStream(), "UTF-8"));
	// StringBuffer stringBuffer = new StringBuffer();
	// String line;
	// while ((line = rd.readLine()) != null) {
	// stringBuffer .append(line);
	// }
	// rd.close();
	// System.out.println("接受到的流是：" + stringBuffer + "—-" + status);
	// return line;
	// } catch (Exception e) {
	// throw new RuntimeException("error",e);
	// }
	// }

	public static final String submitPic(CameraSubmitInfo info) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(
					"http://www.114crj.com/manager/rest/passport/capture.php");
			MultipartEntity mulentity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			mulentity.addPart("imei", new StringBody(TelephonyState
					.getInstance().getIMEI()));
			mulentity.addPart("expressName",
					new StringBody(info.getExpressName(),Charset.forName("UTF-8")));
			mulentity.addPart("expressAdress",
					new StringBody(info.getExpressAddress(),Charset.forName("UTF-8")));
			mulentity.addPart("expressCode",
					new StringBody(info.getExpressCode(),Charset.forName("UTF-8")));
			// 添加图片表单数据
			FileBody filebody = new FileBody(
					new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
			mulentity.addPart("pic", filebody);
			httpPost.setEntity(mulentity);
			HttpResponse response = httpclient.execute(httpPost);
			String strResult = EntityUtils.toString(response.getEntity());
			JSONObject jObj = new JSONObject(strResult);
			System.out.println("接受到的流是：" + jObj.getString("Message"));
			System.out.println("接受到的流是：" + strResult + "—-"
					+ response.getStatusLine().getStatusCode());
			return strResult;
		} catch (Exception e) {
			throw new RuntimeException("error", e);
		}
	}

}
